package com.qkst.website.common.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author lihao
 * @description cookie常用工具类
 * @date 2017-04-26
 */
public final class CookieUtil {

	/**
	 * 设置cookie
	 * @param response
	 * @param key  cookie名字
	 * @param value cookie值
	 * @param maxAge cookie生命周期  以秒为单位
	 */
	public static void addCookie(HttpServletResponse response,String key,String value,int maxAge){
	    Cookie cookie = new Cookie(key,value);
	    cookie.setPath("/");//设置路径，这个路径即该工程下都可以访问该cookie 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
	    if(maxAge>0)  cookie.setMaxAge(maxAge);
	    response.addCookie(cookie);
	}
	/**
	 * 根据cookieName获取cookie值
	 * @param HttpServletRequest request
	 * @param cookie的名称  cookieName 
	 * @return String
	 */
	public static String getCookie(HttpServletRequest request,
			String cookieName) {
		String result = "";
		if (request == null || StringUtils.isBlank(cookieName)) {
			return result;
		}
		Cookie[] cookies = request.getCookies();//获取所有cookies
		if (cookies != null) {
			for (Cookie c : cookies) {
				if (c.getName().equals(cookieName)) {
					result = c.getValue() != null ? c.getValue() : "";
					break;
				}
			}
		}

		return result;
	}

	/**
	 * 设置cookie失效
	 * @param response
	 * @param cookieName
	 */
	public static void invalidCookie(HttpServletResponse response, String cookieName) {
		// 删除cookie,立即过期
		Cookie cookie = new Cookie(cookieName, null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
	}
}